package com.weir.workdemo.work01.future.forkjoin;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveAction;

/**
 * @author weir
 */
@Slf4j
@AllArgsConstructor
public class ComputeTask extends RecursiveAction {

    public static final int THRESHOLD = 10;
    private int start;

    private int end;

    private List<Integer> list;



    @Override
    protected void compute() {
        if ((end - start) <= THRESHOLD) {
            doCompute(start, end, list);
        } else {
            int middle = (start + end) / 2;
            invokeAll(new ComputeTask(start, middle, list), new ComputeTask(middle + 1, end, list));
        }
    }

    private void doCompute(int start, int end, List<Integer> list) {
        List<Integer> subList = list.subList(start, end);
        log.info(subList.toString());
    }

    public static void main(String[] args) {
        List<Integer> testList = new ArrayList<>(100);
        for (int i = 0; i <= 100; i++) {
            testList.add(i);
        }
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Void> submit = forkJoinPool.submit(new ComputeTask(0, 100, testList));
        submit.invoke();
    }
}
